package com.kongxx.struts2study.login;

import com.kongxx.struts2study.common.web.action.BaseAction;
import com.kongxx.struts2study.login.jcaptcha.MyCaptchaService;
import com.octo.captcha.service.CaptchaServiceException;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public final class LoginAction extends BaseAction implements ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = 1L;

	protected HttpServletRequest request;

	protected HttpServletResponse response;

	private String username;

	private String password;

	private String jcaptcha;

	public String toLogin() {
		return SUCCESS;
	}

	public String doLogin() {
		System.out.println("username: " + username);
		System.out.println("password: " + password);
		System.out.println("jcaptcha: " + jcaptcha);

		String captchaId = request.getSession().getId();
		boolean bln = true;
		try {
			bln = MyCaptchaService.getImageCaptchaService().validateResponseForID(captchaId, jcaptcha);
			System.out.println(bln);
		} catch (Exception ex) {
			bln = false;
			this.addActionError(ex.getMessage());
			return INPUT;
		}

		if(username != null && username.equals("Admin") &&
			password != null && password.equals("Admin") && bln) {
			return SUCCESS;
		} else {
			this.addActionError("Login failed.");
			return INPUT;
		}
	}
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}

	public String getJcaptcha() {
		return jcaptcha;
	}

	public void setJcaptcha(String jcaptcha) {
		this.jcaptcha = jcaptcha;
	}
}